package com.dctp.ems.controller;

import com.dctp.common.cache.UserCache;
import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.utils.NumberUtil;
import com.dctp.common.utils.StringUtil;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Path("/riskMetric")
public class RiskMetricController extends BaseController {

    /**
     * GET /riskMetric/list
     * 分页查询风控指标
     */
    public void list() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        Long userId = getParaToLong("user_id");
        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (userId != null) {
            where.append(" AND user_id = ?");
            params.add(userId);
        }

        String startTime = getPara("start_time");
        String endTime = getPara("end_time");
        if (StringUtil.isNotEmpty(startTime)) {
            where.append(" AND update_time >= ?");
            params.add(startTime);
        }
        if (StringUtil.isNotEmpty(endTime)) {
            where.append(" AND update_time <= ?");
            params.add(endTime);
        }

        String select = "SELECT * ";
        String from = "FROM dctp_risk_metric" + where + " ORDER BY id DESC";
        var p = Db.paginate(page, pageSize, select, from, params.toArray());

        List<Record> list = p.getList();
        if (list != null && !list.isEmpty()) {
            for (Record r : list) {
                // 格式化时间
                r.set("user", UserCache.getBasic(r.getLong("user_id")));
            }
        }
        renderJson(JsonResult.successWithData(
            new PageResult<>(p.getList(), p.getTotalRow(), pageSize, page)
        ));
    }

    /**
     * POST /riskMetric/add
     * 添加风控指标
     */
    @Before(Tx.class)
    public void add() {
        Record body = jsonBody();
        if (body.get("user_id") == null) {
            renderJson(JsonResult.failWithMessage("user_id不能为空"));
            return;
        }
        if (!checkRiskMetricDecimal(body)) {
            renderJson(JsonResult.failWithMessage("风控线参数必须为数值且不能为负数"));
            return;
        }
        // 检查唯一
        Long exist = Db.queryLong("SELECT id FROM dctp_risk_metric WHERE user_id=?", body.getLong("user_id"));
        if (exist != null) {
            renderJson(JsonResult.failWithMessage("该用户风控指标已存在"));
            return;
        }
        body.set("create_time", DateUtil.now());
        if (!Db.save("dctp_risk_metric", body)) {
            throw new RuntimeException("新增风控指标失败");
        }
        renderJson(JsonResult.success());
    }

    /**
     * POST /riskMetric/update/:id
     * 更新风控指标
     */
    @Before(Tx.class)
    public void update() {
        Long id = getParaToLong(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        Record body = jsonBody();
        if (body.getColumns().isEmpty()) {
            renderJson(JsonResult.failWithMessage("无有效字段"));
            return;
        }
        if (!checkRiskMetricDecimal(body)) {
            renderJson(JsonResult.failWithMessage("风控线参数必须为数值且不能为负数"));
            return;
        }
        body.set("id", id)
            .set("update_time", DateUtil.now());
        boolean updated = Db.update("dctp_risk_metric", body);
        if (!updated) {
            renderJson(JsonResult.failWithMessage("更新失败或记录不存在"));
            return;
        }
        renderJson(JsonResult.success());
    }

    /**
     * POST /riskMetric/delete/:id
     * 删除风控指标
     */
    @Before(Tx.class)
    public void delete() {
        Long id = getParaToLong(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        int r = Db.update("DELETE FROM dctp_risk_metric WHERE id=?", id);
        if (r == 0) {
            renderJson(JsonResult.failWithMessage("删除失败或记录不存在"));
        } else {
            renderJson(JsonResult.success());
        }
    }

    /**
     * GET /riskMetric/all
     * 获取所有启用的风控指标
     */
    public void all() {
        List<Record> list = Db.find("SELECT * FROM dctp_risk_metric WHERE enabled=1 ORDER BY id DESC");
        renderJson(JsonResult.successWithData(list));
    }

    private boolean checkRiskMetricDecimal(Record body) {
        String[] keys = {"dyn_warning_line", "dyn_forbid_open_line", "dyn_force_close_line",
                "daily_loss_warning_line", "daily_loss_forbid_open", "daily_loss_force_close"};
        for (String key : keys) {
            Object v = body.get(key);
            if (v != null) {
                if (!NumberUtil.isValidDecimal(v)) return false;
                try {
                    if (new BigDecimal(v.toString()).compareTo(BigDecimal.ZERO) < 0) return false;
                } catch (Exception e) {
                    return false;
                }
            }
        }
        return true;
    }
}
